package cn.devcat.sso.config.security.handler;

import java.util.Collection;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import cn.devcat.sso.config.security.SecurityMessageUtil;

@Component
public class DevcatAccessDecisionManager implements AccessDecisionManager {

  @Override
  public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
    throws AccessDeniedException, InsufficientAuthenticationException {
    if (authentication == null) {
      throw new AccessDeniedException(SecurityMessageUtil.NO_ACCESS);
    }
    for (ConfigAttribute configAttribute : configAttributes) {
      String attribute = configAttribute.getAttribute();
      if ("ROLE_ANONYMOUS".equals(attribute)) {
        return;
      }
      Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
      for (GrantedAuthority authority : authorities) {
        String temp = authority.getAuthority();
        if (temp.equals(attribute)) {
          return;
        }
      }
    }
    throw new AccessDeniedException(SecurityMessageUtil.NO_ACCESS);

  }

  @Override
  public boolean supports(ConfigAttribute attribute) {
    return false;
  }

  @Override
  public boolean supports(Class<?> clazz) {
    return FilterInvocation.class.isAssignableFrom(clazz);
  }


}
